package com.jiaqiang.chatgpt.session.defaults;

import com.jiaqiang.chatgpt.IOpenAiApi;
import com.jiaqiang.chatgpt.interceptor.OpenAiInterceptor;
import com.jiaqiang.chatgpt.session.GptConfiguration;
import com.jiaqiang.chatgpt.session.UserOpenAiSession;
import com.jiaqiang.chatgpt.session.UserSessionOpenAiSessionFactory;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86187
 * Date: 2024-03-28
 * Time: 14:28
 */
@Slf4j
@Component
public class DefaultUserSessionOpenAiSessionFactory implements UserSessionOpenAiSessionFactory {

    private final GptConfiguration gptConfiguration;

    public DefaultUserSessionOpenAiSessionFactory(GptConfiguration gptConfiguration) {
        this.gptConfiguration = gptConfiguration;
    }

    /**
     * 用于创建一个 OpenAI 会话，返回类型为 OpenAiSession
     * @return OpenAiSession 具体的 OpenAI 会话
     */
    @Override
    public UserOpenAiSession openSession() {
        // 1. 日志配置 设置日志级别为 HEADERS，以便记录请求头信息
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        log.info("代理 host = {}, port = {}", gptConfiguration.getHost(), gptConfiguration.getPort());

        // 2. 开启 Http 客户端
        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                // OpenAiInterceptor 拦截器用于添加 OpenAI 接口所需的认证信息，包括 API 密钥和身份验证令牌
                .addInterceptor(new OpenAiInterceptor(gptConfiguration.getSessionKey()))
                // 使用 HttpLoggingInterceptor 创建一个日志拦截器，并设置日志级别为 HEADERS，以便记录请求头信息。
                .addInterceptor(httpLoggingInterceptor)
                // 连接超时时间 450s
                .connectTimeout(450, TimeUnit.SECONDS)
                // 写入超时时间 450s
                .writeTimeout(450, TimeUnit.SECONDS)
                // 读取超时时间 450s
                .readTimeout(450, TimeUnit.SECONDS)
                // 访问chatgpt接口可能需要设置代理.
                .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(gptConfiguration.getHost(), gptConfiguration.getPort())))
                .build();
        // 必须要的一不, createRequestFactory 方法用到了
        gptConfiguration.setOkHttpClient(okHttpClient);

        // 3. 创建 API 服务. 使用 Retrofit 框架创建一个 API 服务
        IOpenAiApi openAiApi = new Retrofit.Builder()
                // 指定了 OpenAI API 的基础 URL
                .baseUrl(gptConfiguration.getApiHost())
                // 上述创建的 OkHttpClient 实例
                .client(okHttpClient)
                // RxJava 2 的调用适配器工厂 以及 Jackson 的 JSON 转换器工厂
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(JacksonConverterFactory.create())
                // 创建了一个 IOpenAiApi 接口的实例
                .build().create(IOpenAiApi.class);

        gptConfiguration.setOpenAiApi(openAiApi);

        return new DefaultUserSessionOpenAiSession(gptConfiguration);
    }
}
